package com.hscm.boss.mvc.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hscm.boss.common.client.RedisClient;
import com.hscm.boss.common.consants.KeyConstant;
import com.hscm.boss.common.enums.ResponseCode;
import com.hscm.boss.mvc.model.AjaxResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

//验证拦截器  这是SpringMVC中的拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource // 使用redis的原因是Token放在redis这中
    private RedisClient redisClient;

    //验证Token
    @Override //preHandle表示被拦截之前执行代码
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        // 1 放行预检请求OPTIONS  这里的OPTIONS写错就会出现跨域错误
        if ("OPTIONS".equals(request.getMethod())) {//判断是否是预检请求 （不传值 不传Token）
            return true;
        }

        // 2 获取header中的 operatorId  Authorization
        String operatorId = request.getHeader("operatorId");
        String authorization = request.getHeader("Authorization");

        if (StrUtil.isNotBlank(operatorId) && StrUtil.isNotBlank(authorization)
                && authorization.startsWith("Bearer")) {
            //前端的jwt
            String requestJwt = authorization.substring(7);

            //从redis中取数据
            String redisJwt = redisClient.getHashField(KeyConstant.TOKEN_OPERATOR + operatorId, "jwt");

            //StrUtil.isNotBlank(requestJwt) 含义是防止出现空指针异常
            if (StrUtil.isNotBlank(requestJwt) && requestJwt.equals(redisJwt)) {
                return true; //说明身份认证是正确的
            }
        }


        //jwt 是无效的 需要让操作员重新登录
        AjaxResult fail = AjaxResult.fail(ResponseCode.LOGIN_TOKEN_INVALID);
        //把失败的信息返回给前端  手动转成JSON格式
        String responseText = JSONUtil.toJsonStr(fail);

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(responseText);
        out.flush();
        out.close();

        return false;
    }
}
